package com.bingxue.edu.management.education.controller;

import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.URLUtil;
import com.bingxue.edu.framework.common.model.PageQuery;
import com.bingxue.edu.framework.common.model.Pagination;
import com.bingxue.edu.framework.common.model.Response;
import com.bingxue.edu.framework.common.util.ValidationUtils;
import com.bingxue.edu.framework.excel.util.ExcelUtil;
import com.bingxue.edu.framework.security.ApiResource;
import com.bingxue.edu.management.education.model.entity.Enrollment;
import com.bingxue.edu.management.education.model.query.EnrollClassQuery;
import com.bingxue.edu.management.education.model.query.EnrollLessonQuery;
import com.bingxue.edu.management.education.model.query.EnrollmentIdQuery;
import com.bingxue.edu.management.education.model.query.EnrollmentQuery;
import com.bingxue.edu.management.education.model.req.EnrollPermissionImportReq;
import com.bingxue.edu.management.education.model.req.EnrollSellerUpdateReq;
import com.bingxue.edu.management.education.model.resp.EnrollClassResp;
import com.bingxue.edu.management.education.model.resp.EnrollLessonResp;
import com.bingxue.edu.management.education.model.resp.EnrollPermissionImportParseResp;
import com.bingxue.edu.management.education.model.resp.EnrollmentDetailResp;
import com.bingxue.edu.management.education.model.resp.EnrollmentExportResp;
import com.bingxue.edu.management.education.model.resp.EnrollmentResp;
import com.bingxue.edu.management.education.service.EnrollPermissionService;
import com.bingxue.edu.management.education.service.EnrollmentService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.constraints.NotNull;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.ClassPathResource;
import org.springframework.http.MediaType;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

/**
 * 报名记录
 *
 * @author zq
 * @since 2024/08/26
 */
@Slf4j
@Tag(name = "报名记录")
@RestController
@RequestMapping("/education/enrollment")
@RequiredArgsConstructor
public class EnrollmentController {

    private final EnrollmentService enrollmentService;
    private final EnrollPermissionService enrollPermissionService;

    @Operation(summary = "分页查询报名记录")
    @ApiResource("edu:enroll:read")
    @GetMapping("/page")
    public Response<Pagination<EnrollmentResp>> page(EnrollmentQuery query, @Validated PageQuery pageQuery) {
        return Response.success(Pagination.of(enrollmentService.getEnrollmentPage(query, pageQuery)));
    }

    @Operation(summary = "导出报名记录")
    @ApiResource("edu:enroll:export")
    @GetMapping("/export")
    public void export(EnrollmentQuery query, HttpServletResponse response) {
        List<EnrollmentExportResp> records = enrollmentService.getEnrollmentList(query).stream().map(EnrollmentExportResp::of).toList();
        ExcelUtil.export(records, "报名记录", EnrollmentExportResp.class, response);
    }

    @Operation(summary = "查询报名id")
    @ApiResource("edu:enroll:read")
    @GetMapping("/getEnrollmentId")
    public Response<String> getEnrollmentId(@Validated EnrollmentIdQuery query) {
        Enrollment enrollment = enrollmentService.getStudentEnrollment(query.getClassId(), query.getStudentId());
        ValidationUtils.throwIfNull(enrollment, "报名信息不存在");
        return Response.success(enrollment.getId());
    }

    @Operation(summary = "查询报名详情")
    @ApiResource("edu:enroll:read")
    @GetMapping("/detail/{id}")
    public Response<EnrollmentDetailResp> getDetailById(@PathVariable String id) {
        return Response.success(enrollmentService.getDetailById(id));
    }

    @Operation(summary = "查询学生报名班级分页")
    @ApiResource("edu:enroll:read")
    @GetMapping("/enroll-class/page")
    public Response<Pagination<EnrollClassResp>> getEnrollClassPage(@Validated EnrollClassQuery query, @Validated PageQuery pageQuery) {
        Pagination<EnrollClassResp> page = enrollmentService.getEnrollClassPage(query, pageQuery, EnrollClassResp.class);
        return Response.success(page);
    }

    @Operation(summary = "查询学生报名班级")
    @ApiResource("edu:enroll:read")
    @GetMapping("/enroll-class/detail/{enrollmentId}")
    public Response<EnrollClassResp> getEnrollClassPage(@PathVariable String enrollmentId) {
        EnrollClassQuery enrollClassQuery = new EnrollClassQuery();
        enrollClassQuery.setEnrollmentId(enrollmentId);
        return Response.success(enrollmentService.getEnrollClass(enrollClassQuery));
    }

    @Operation(summary = "查询学生报名课次")
    @ApiResource("edu:enroll:read")
    @GetMapping("/enroll-lesson-list")
    public Response<List<EnrollLessonResp>> getEnrollLessonList(@Validated EnrollLessonQuery query) {
        List<EnrollLessonResp> list = enrollmentService.getEnrollLessonList(query);
        return Response.success(list);
    }

    @Operation(summary = "添加顾问")
    @ApiResource("edu:enroll:set-seller")
    @PostMapping("/addSeller")
    public Response<Void> addSeller(@Validated EnrollSellerUpdateReq req) {
        enrollmentService.updateSeller(req);
        return Response.success();
    }


    @Operation(summary = "下载报名权限导入模板", description = "下载报名权限导入模板")
    @ApiResource("edu:enroll:read")
    @GetMapping(value = "downloadEnrollPermissionUserTemplate", produces = MediaType.APPLICATION_OCTET_STREAM_VALUE)
    public void downloadImportEnrollPermissionTemplate(HttpServletResponse response) throws IOException {
        try (InputStream inputStream = new ClassPathResource("templates/import/enrollPermissionImportTemplate.xlsx").getInputStream()) {
            response.setContentType("application/x-msdownload");
            response.setCharacterEncoding("utf-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + URLUtil.encode("报名权限导入模板.xlsx"));
            response.addHeader("Content-Length", String.valueOf(inputStream.available()));
            response.setHeader("Access-Control-Allow-Origin", "*");
            response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
            IoUtil.copy(inputStream, response.getOutputStream());
        } catch (Exception e) {
            log.error("下载下载报名权限导入模板失败：", e);
            throw e;
        }
    }


    @Operation(summary = "解析报名权限导入数据", description = "解析报名权限导入数据")
    @ApiResource("edu:enroll:read")
    @PostMapping(value = "parseImportEnrollPermission")
    public Response<EnrollPermissionImportParseResp> parseImportEnrollPermission(@NotNull(message = "文件不能为空") MultipartFile file) {
        ValidationUtils.throwIf(file::isEmpty, "文件不能为空");
        return Response.success(enrollPermissionService.parseImportEnrollPermission(file));
    }

    @Operation(summary = "导入报名权限", description = "导入报名权限")
    @ApiResource("edu:enroll:read")
    @PostMapping(value = "import")
    public Response<Void> importEnrollPermission(@Validated @RequestBody EnrollPermissionImportReq req) {
        enrollPermissionService.importEnrollPermission(req);
        return Response.success();
    }

}
